<template>
  <view class="recharge-page">
    <!-- 标题区域 -->
    <view class="header">
      <text class="page-title">充币 {{ rechargeInfo.type || 'USDT' }}</text>
    </view>

    <!-- 二维码区域 -->
    <view class="qrcode-section">
      <view class="qrcode-wrapper">
        <!-- 加载状态 -->
        <view v-if="isLoading" class="loading-wrapper">
          <uv-loading-icon mode="spinner" color="#ffffff" size="40"></uv-loading-icon>
          <text class="loading-text">加载中...</text>
        </view>
        
        <!-- 二维码图片 -->
        <image 
          v-else
          class="qrcode-image" 
          :src="qrcodeUrl" 
          mode="aspectFit"
        ></image>
        
        <!-- 中间的 logo -->
        <view v-if="!isLoading && qrcodeUrl" class="qrcode-logo">
          <view class="logo-circle" :class="getLogoColorClass()">
            <text class="logo-text">{{ getLogoText() }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 地址区域 -->
    <view class="address-section">
      <view class="address-label">地址</view>
      <view class="address-row">
        <text class="address-value">{{ rechargeInfo.address || (isLoading ? '加载中...' : '暂无数据') }}</text>
        <view v-if="!isLoading && rechargeInfo.address" class="copy-btn" @click="copyAddress">
          <text class="copy-text">copy</text>
        </view>
      </view>
    </view>

    <!-- 信息列表 -->
    <view class="info-list">
      <!-- 网络 -->
      <view class="info-item">
        <text class="info-label">网络</text>
        <view class="info-value-wrapper">
          <view class="network-logo" :class="getLogoColorClass()">
            <text class="network-logo-text">{{ getLogoText() }}</text>
          </view>
          <text class="info-value">{{ rechargeInfo.network || (isLoading ? '加载中...' : '暂无数据') }}</text>
        </view>
      </view>

      <!-- 最小充币额 -->
      <view class="info-item">
        <view class="info-label-wrapper">
          <text class="info-label">最小充币额</text>
          <view class="info-icon" @click="showMinAmountTip">
            <uv-icon name="info-circle" size="14" color="#ffffff"></uv-icon>
          </view>
        </view>
        <text class="info-value">{{ rechargeInfo.minAmount || (isLoading ? '加载中...' : '暂无数据') }}</text>
      </view>
    </view>

    <!-- 温馨提示 -->
    <view class="tips-section">
      <view class="tips-title">
        <uv-icon name="info-circle" size="18" color="#ff9800"></uv-icon>
        <text class="tips-title-text">温馨提示</text>
      </view>
      <view class="tips-content">
        <text class="tip-item">• 请勿向上述地址充值任何非 {{ rechargeInfo.type || 'USDT' }} 资产，否则资产将不可找回</text>
        <text class="tip-item">• 最小充值金额为 {{ rechargeInfo.minAmount }}，小于最小金额的充值将不会上账</text>
        <text class="tip-item">• 您充值至上述地址后，需要整个网络节点的确认，1次网络确认后到账</text>
        <text class="tip-item">• 充值完成后，请联系客服确认到账</text>
      </view>
    </view>

    <!-- 底部按钮 -->
    <view class="bottom-buttons" :style="{ paddingBottom: (bottomSafePx + 40) + 'px' }">
      <view class="action-btn copy-address-btn" @click="copyAddress">
        <uv-icon name="file-text" size="20" color="#fff"></uv-icon>
        <text class="btn-text">复制地址</text>
      </view>
      <view class="action-btn contact-btn" @click="contactService">
        <uv-icon name="chat" size="20" color="#fff"></uv-icon>
        <text class="btn-text">联系客服</text>
      </view>
    </view>
  </view>
</template>

<script>
import { getRechargeConfigs } from '@/api/user'

export default {
  data() {
    const sys = uni.getSystemInfoSync()
    return {
      bottomSafePx: sys.safeAreaInsets ? sys.safeAreaInsets.bottom : 10,
      
      // 充值信息
      rechargeInfo: {  
        address: '',
        network: '',
        minAmount: '',
        type: ''
      },
      
      // 二维码URL（可以使用在线生成服务或本地生成）
      qrcodeUrl: '',
      
      // 加载状态
      isLoading: false,
    }
  },

  onLoad() {
    this.loadRechargeConfigs()
  },

  methods: {
    /**
     * 加载充值配置信息
     */
    async loadRechargeConfigs() {
      try {
        this.isLoading = true
        
        const response = await getRechargeConfigs()
        console.log('充值配置数据:', response)
        
        // 处理接口返回的数据
        // 从接口返回的data数组的第一个元素中取数据
        let data = null
        if (response && typeof response === 'object') {
          // 如果响应有 data 字段且是数组，取第一个元素
          if (response.data && Array.isArray(response.data) && response.data.length > 0) {
            data = response.data[0]
          } else if (response.data && typeof response.data === 'object' && !Array.isArray(response.data)) {
            // 兼容处理：如果data不是数组，直接使用
            data = response.data
          }
        }
        
        // 更新充值信息
        if (data && data.address) {
          this.rechargeInfo.address = String(data.address).trim()
        }
        
        if (data && data.from) {
          this.rechargeInfo.network = String(data.from).trim()
        }
        if (data && data.type) {
          this.rechargeInfo.type = String(data.type).trim()
        }
        
        if (data && data.min !== undefined && data.min !== null) {
          // 如果接口返回的是数字，需要格式化
          if (typeof data.min === 'number') {
            this.rechargeInfo.minAmount = `${data.min}`
          } else {
            // 如果是字符串，检查是否已包含 USDT
            const minAmountStr = String(data.min).trim()
              this.rechargeInfo.minAmount = minAmountStr;
          }
        }
        
        // 处理二维码
        if (data && data.qrcode) {
          const qrcode = String(data.qrcode).trim()
          // 如果接口返回的是base64格式
          if (qrcode.startsWith('data:image') || qrcode.startsWith('base64')) {
            this.qrcodeUrl = qrcode
          } else if (qrcode.startsWith('http://') || qrcode.startsWith('https://')) {
            // 如果是完整的URL，直接使用
            this.qrcodeUrl = qrcode
          } else {
            // 可能是相对路径或base64字符串（没有前缀）
            this.qrcodeUrl = qrcode
          }
        } else if (this.rechargeInfo.address) {
          // 如果接口没有返回二维码，根据地址生成
          this.generateQRCode()
        }
        
      } catch (error) {
        console.error('加载充值配置失败:', error)
        uni.showToast({
          title: error.message || '加载充值配置失败',
          icon: 'none',
          duration: 2000
        })
        
        // 加载失败时清空数据
        this.rechargeInfo = {
          address: '',
          network: '',
          minAmount: '',
          type: ''
        }
        this.qrcodeUrl = ''
      } finally {
        this.isLoading = false
      }
    },

    /**
     * 生成二维码
     */
    generateQRCode() {
      // 使用在线二维码生成服务
      const address = this.rechargeInfo.address
      if (!address) {
        console.warn('地址为空，无法生成二维码')
        return
      }
      // 使用免费的二维码生成API
      this.qrcodeUrl = `https://api.qrserver.com/v1/create-qr-code/?size=400x400&data=${encodeURIComponent(address)}`
      
      console.log('生成二维码URL:', this.qrcodeUrl)
    },

    /**
     * 复制地址
     */
    copyAddress() {
      if (!this.rechargeInfo.address) {
        uni.showToast({
          title: '地址为空，无法复制',
          icon: 'none'
        })
        return
      }
      
      uni.setClipboardData({
        data: this.rechargeInfo.address,
        success: () => {
          uni.showToast({
            title: '地址已复制',
            icon: 'none',
            duration: 2000
          })
        },
        fail: (err) => {
          console.error('复制失败:', err)
          uni.showToast({
            title: '复制失败',
            icon: 'none'
          })
        }
      })
    },

    /**
     * 获取logo文字
     */
    getLogoText() {
      const type = (this.rechargeInfo.type || '').toUpperCase()
      if (type.includes('SOL') || type.includes('SOLANA')) {
        return '◎'
      } else if (type.includes('USDT') || type.includes('USDC')) {
        return '₮'
      } else if (type.includes('BTC') || type.includes('BITCOIN')) {
        return '₿'
      } else if (type.includes('ETH') || type.includes('ETHEREUM')) {
        return 'Ξ'
      }
      return '₮'
    },

    /**
     * 获取logo颜色类名
     */
    getLogoColorClass() {
      const type = (this.rechargeInfo.type || '').toUpperCase()
      if (type.includes('SOL') || type.includes('SOLANA')) {
        return 'solana-color'
      } else if (type.includes('USDT') || type.includes('USDC')) {
        return 'usdt-color'
      } else if (type.includes('BTC') || type.includes('BITCOIN')) {
        return 'btc-color'
      } else if (type.includes('ETH') || type.includes('ETHEREUM')) {
        return 'eth-color'
      }
      return 'usdt-color'
    },

    /**
     * 显示最小充币额提示
     */
    showMinAmountTip() {
      uni.showToast({
        title: `最小充值金额为 ${this.rechargeInfo.minAmount}`,
        icon: 'none',
        duration: 2000
      })
    },

    /**
     * 联系客服
     */
    contactService() {
      uni.navigateTo({
        url: '/subPages/help/customer-service'
      })
    },

    /**
     * 保存二维码图片
     */
    saveQRCode() {
      if (!this.qrcodeUrl) {
        uni.showToast({
          title: '二维码未生成',
          icon: 'none'
        })
        return
      }

      uni.showLoading({
        title: '保存中...'
      })

      // #ifdef H5
      this.saveQRCodeH5()
      // #endif

      // #ifdef APP-PLUS
      this.saveQRCodeApp()
      // #endif

      // #ifdef MP-WEIXIN
      this.saveQRCodeMiniProgram()
      // #endif
    },

    /**
     * H5端保存二维码
     */
    saveQRCodeH5() {
      // 创建一个隐藏的 canvas 来绘制图片
      const img = new Image()
      img.crossOrigin = 'anonymous'
      img.onload = () => {
        const canvas = document.createElement('canvas')
        canvas.width = img.width
        canvas.height = img.height
        const ctx = canvas.getContext('2d')
        ctx.drawImage(img, 0, 0)
        
        // 转换为 blob 并下载
        canvas.toBlob((blob) => {
          const url = URL.createObjectURL(blob)
          const link = document.createElement('a')
          link.href = url
          link.download = `USDT_${this.rechargeInfo.network.replace(/[^a-zA-Z0-9]/g, '_')}_${Date.now()}.png`
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link)
          URL.revokeObjectURL(url)
          
          uni.hideLoading()
          uni.showToast({
            title: '保存成功',
            icon: 'success'
          })
        }, 'image/png')
      }
      img.onerror = () => {
        uni.hideLoading()
        uni.showToast({
          title: '保存失败，请长按图片保存',
          icon: 'none'
        })
      }
      img.src = this.qrcodeUrl
    },

    /**
     * APP端保存二维码
     */
    saveQRCodeApp() {
      // 先下载图片到本地
      uni.downloadFile({
        url: this.qrcodeUrl,
        success: (downloadRes) => {
          if (downloadRes.statusCode === 200) {
            // 保存到相册
            uni.saveImageToPhotosAlbum({
              filePath: downloadRes.tempFilePath,
              success: () => {
                uni.hideLoading()
                uni.showToast({
                  title: '已保存到相册',
                  icon: 'success'
                })
              },
              fail: (err) => {
                uni.hideLoading()
                console.error('保存到相册失败:', err)
                // 可能是权限问题
                if (err.errMsg && err.errMsg.includes('auth')) {
                  uni.showModal({
                    title: '提示',
                    content: '需要您授权保存图片到相册',
                    confirmText: '去设置',
                    success: (res) => {
                      if (res.confirm) {
                        uni.openSetting()
                      }
                    }
                  })
                } else {
                  uni.showToast({
                    title: '保存失败',
                    icon: 'none'
                  })
                }
              }
            })
          } else {
            uni.hideLoading()
            uni.showToast({
              title: '下载失败',
              icon: 'none'
            })
          }
        },
        fail: (err) => {
          uni.hideLoading()
          console.error('下载图片失败:', err)
          uni.showToast({
            title: '下载失败',
            icon: 'none'
          })
        }
      })
    },

    /**
     * 小程序端保存二维码
     */
    saveQRCodeMiniProgram() {
      uni.downloadFile({
        url: this.qrcodeUrl,
        success: (downloadRes) => {
          if (downloadRes.statusCode === 200) {
            uni.saveImageToPhotosAlbum({
              filePath: downloadRes.tempFilePath,
              success: () => {
                uni.hideLoading()
                uni.showToast({
                  title: '已保存到相册',
                  icon: 'success'
                })
              },
              fail: (err) => {
                uni.hideLoading()
                if (err.errMsg && err.errMsg.includes('auth')) {
                  uni.showModal({
                    title: '提示',
                    content: '需要您授权保存图片到相册',
                    confirmText: '去授权',
                    success: (res) => {
                      if (res.confirm) {
                        uni.openSetting()
                      }
                    }
                  })
                } else {
                  uni.showToast({
                    title: '保存失败',
                    icon: 'none'
                  })
                }
              }
            })
          } else {
            uni.hideLoading()
            uni.showToast({
              title: '下载失败',
              icon: 'none'
            })
          }
        },
        fail: () => {
          uni.hideLoading()
          uni.showToast({
            title: '下载失败',
            icon: 'none'
          })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.recharge-page {
  min-height: 100vh;
  background: #000000;
  padding: 40rpx 32rpx;
  padding-bottom: 200rpx;
  position: relative;
}

/* 标题区域 */
.header {
  margin-bottom: 48rpx;
  text-align: center;

  .page-title {
    font-size: 40rpx;
    font-weight: 700;
    color: #ffffff;
    letter-spacing: 1rpx;
  }
}

/* 二维码区域 */
.qrcode-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 48rpx;

  .qrcode-wrapper {
    position: relative;
    padding: 32rpx;
    background: #ffffff;
    border-radius: 24rpx;
    display: flex;
    align-items: center;
    justify-content: center;

    .qrcode-image {
      width: 480rpx;
      height: 480rpx;
      display: block;
      border-radius: 16rpx;
    }

    .loading-wrapper {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      width: 480rpx;
      height: 480rpx;
      gap: 24rpx;

      .loading-text {
        font-size: 28rpx;
        color: #ffffff;
        font-weight: 500;
      }
    }

    .qrcode-logo {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      z-index: 2;
      
      .logo-circle {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 100rpx;
        height: 100rpx;
        background: #ffffff;
        border-radius: 50%;
        box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);

        .logo-text {
          font-size: 52rpx;
          font-weight: bold;
          line-height: 1;
        }

        &.solana-color .logo-text {
          color: #9945ff;
        }

        &.usdt-color .logo-text {
          color: #26a17b;
        }

        &.btc-color .logo-text {
          color: #f7931a;
        }

        &.eth-color .logo-text {
          color: #627eea;
        }
      }
    }
  }
}

/* 地址区域 */
.address-section {
  margin-bottom: 32rpx;
  padding: 32rpx;
  background: rgba(255, 255, 255, 0.05);
  border-radius: 16rpx;

  .address-label {
    font-size: 28rpx;
    color: #ffffff;
    margin-bottom: 20rpx;
    font-weight: 500;
  }

  .address-row {
    display: flex;
    align-items: center;
    gap: 16rpx;

    .address-value {
      flex: 1;
      font-size: 26rpx;
      color: #ffffff;
      font-family: 'SF Mono', 'Monaco', 'Courier New', monospace;
      word-break: break-all;
      line-height: 1.6;
      opacity: 0.9;
    }

    .copy-btn {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 80rpx;
      height: 80rpx;
      background: rgba(255, 255, 255, 0.08);
      border: 1rpx solid rgba(255, 255, 255, 0.15);
      border-radius: 50%;
      flex-shrink: 0;
      cursor: pointer;
      transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
      position: relative;
      overflow: hidden;

      &::before {
        content: '';
        position: absolute;
        inset: 0;
        background: linear-gradient(135deg, rgba(255, 255, 255, 0.1), rgba(255, 255, 255, 0.05));
        opacity: 0;
        transition: opacity 0.3s ease;
      }

      &:active {
        transform: scale(0.92);
        background: rgba(255, 255, 255, 0.12);
        border-color: rgba(255, 255, 255, 0.25);
        
        &::before {
          opacity: 1;
        }
      }

      .copy-text {
        font-size: 20rpx;
        font-weight: 600;
        color: #ffffff;
        letter-spacing: 0.5rpx;
        text-transform: uppercase;
        position: relative;
        z-index: 1;
      }
    }
  }
}

/* 信息列表 */
.info-list {
  display: flex;
  flex-direction: column;
  gap: 0;
}

.info-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 32rpx 0;
  border-bottom: 1rpx solid rgba(255, 255, 255, 0.1);

  &:last-child {
    border-bottom: none;
  }

  .info-label-wrapper {
    display: flex;
    align-items: center;
    gap: 8rpx;

    .info-label {
      font-size: 28rpx;
      color: #ffffff;
      font-weight: 500;
    }

    .info-icon {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 32rpx;
      height: 32rpx;
      cursor: pointer;
      opacity: 0.7;
      transition: opacity 0.3s ease;

      &:active {
        opacity: 1;
      }
    }
  }

  .info-label {
    font-size: 28rpx;
    color: #ffffff;
    font-weight: 500;
  }

  .info-value-wrapper {
    display: flex;
    align-items: center;
    gap: 12rpx;

    .network-logo {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 40rpx;
      height: 40rpx;
      border-radius: 8rpx;

      .network-logo-text {
        font-size: 24rpx;
        font-weight: bold;
        line-height: 1;
      }

      &.solana-color {
        background: rgba(153, 69, 255, 0.2);
        .network-logo-text {
          color: #9945ff;
        }
      }

      &.usdt-color {
        background: rgba(38, 161, 123, 0.2);
        .network-logo-text {
          color: #26a17b;
        }
      }

      &.btc-color {
        background: rgba(247, 147, 26, 0.2);
        .network-logo-text {
          color: #f7931a;
        }
      }

      &.eth-color {
        background: rgba(98, 126, 234, 0.2);
        .network-logo-text {
          color: #627eea;
        }
      }
    }
  }

  .info-value {
    font-size: 28rpx;
    color: #ffffff;
    font-weight: 500;
    text-align: right;
  }
}

/* 温馨提示 */
.tips-section {
  margin-top: 48rpx;
  padding: 32rpx;
  background: rgba(255, 152, 0, 0.1);
  border-radius: 16rpx;
  border: 1rpx solid rgba(255, 152, 0, 0.2);

  .tips-title {
    display: flex;
    align-items: center;
    gap: 12rpx;
    margin-bottom: 24rpx;

    .tips-title-text {
      font-size: 30rpx;
      font-weight: 600;
      color: #ff9800;
      letter-spacing: 0.5rpx;
    }
  }

  .tips-content {
    display: flex;
    flex-direction: column;
    gap: 16rpx;

    .tip-item {
      font-size: 26rpx;
      line-height: 1.8;
      color: rgba(255, 255, 255, 0.9);
      font-weight: 400;
      letter-spacing: 0.3rpx;
    }
  }
}

/* 底部按钮 */
.bottom-buttons {
  position: fixed;
  right: 0;
  bottom: 0;
  left: 0;
  display: flex;
  gap: 20rpx;
  padding: 24rpx 32rpx 0;
  background: rgba(0, 0, 0, 0.95);
  backdrop-filter: blur(20rpx);
  -webkit-backdrop-filter: blur(20rpx);
  box-shadow: 0 -4rpx 20rpx rgba(0, 0, 0, 0.3);
  border-top: 1rpx solid rgba(255, 255, 255, 0.1);
  z-index: 100;
}

.action-btn {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12rpx;
  height: 88rpx;
  border-radius: 44rpx;
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
  overflow: hidden;

  &::before {
    content: '';
    position: absolute;
    inset: 0;
    background: linear-gradient(135deg, rgba(255, 255, 255, 0.2), rgba(255, 255, 255, 0));
    opacity: 0;
    transition: opacity 0.3s ease;
  }

  &:active {
    transform: translateY(2rpx) scale(0.98);
    
    &::before {
      opacity: 1;
    }
  }

  .btn-text {
    font-size: 28rpx;
    font-weight: 600;
    color: #fff;
    letter-spacing: 1rpx;
    position: relative;
    z-index: 1;
  }

  &.copy-address-btn {
    background: linear-gradient(135deg, #06cbb6 0%, #04a89e 100%);
    box-shadow: 0 4rpx 16rpx rgba(6, 203, 182, 0.4);

    &:active {
      box-shadow: 0 2rpx 8rpx rgba(6, 203, 182, 0.5);
    }
  }

  &.contact-btn {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    box-shadow: 0 4rpx 16rpx rgba(102, 126, 234, 0.4);

    &:active {
      box-shadow: 0 2rpx 8rpx rgba(102, 126, 234, 0.5);
    }
  }
}
</style>


